import React from 'react';
import { Button, Spin } from 'antd';
import { inject, observer } from 'mobx-react';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import { WeaTop, WeaTab, WeaTable, WeaRightMenu, WeaDialog, WeaBrowser, WeaNewScroll, WeaFormItem, WeaSearchGroup, WeaLocaleProvider } from 'ecCom';
import { toJS } from 'mobx';

const Table = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
import TabComponent from './common/TabComponent';


/**
 * 发文台账
 */
@inject('accountListStore')
@observer
class AccountListComponent extends React.Component {
  componentDidMount() {
    const { accountListStore, location } = this.props;
    if (location.query.inPortal) {
      accountListStore.setMobxState({ inPortal: true, pageSize: 5 });
    }
    accountListStore.buildSearchCondition();
    accountListStore.doSearch();
    accountListStore.postWebSendDocCondition();
  }

  renderRightAndDropMenus() {
    const { accountListStore } = this.props;
    const datas = [
      {
        key: '1',
        disabled: false,
        icon: <i className="icon-coms-search" />,
        content: getLabel('197', '搜索'),
        onClick: () => {
          const params = this.tabComp.wrappedInstance.getFormParams();
          accountListStore.doSearch(params, true);
        },
      },
    ];
    return datas;
  }

  renderSearchAdButtons() {
    const { accountListStore } = this.props;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@33y1s2@search`} type="primary" onClick={() => accountListStore.doSearch({}, true)}>{getLabel('197', '搜索')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kfxsjk@reset`} type="ghost" onClick={() => accountListStore.resetForm()}>{getLabel('2022', '重置')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f7mayk@clean`} type="ghost" onClick={() => accountListStore.searchStore.changeShowSearchAd(false)}>{getLabel('31129', '取消')}</Button>),
    ];
  }

  render() {
    const { accountListStore } = this.props;
    const { tableStore, changeDailogStatus, visiable, selectedRowKeys, onOperatesClick, getDialogTable, rowSelection, reasonDialogShow, repeal,
      backoutForm, inPortal, doSearch, ReasonDialogStatus,
    } = accountListStore;
    if (inPortal) {
      return this.getTable(false);
    }
    return (
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@m1exxs`}
        datas={this.renderRightAndDropMenus()}
      >
        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@zyp5c4`}
          title={getLabel('383653', '公文台账')}
          icon={<i className="icon-coms-official" />}
          iconBgcolor="#f14a2d"
        >
          <TabComponent ecId={`${this && this.props && this.props.ecId || ''}_TabComponent@p1e8iz`}
            ref={refs => this.tabComp = refs}
            getDataList={params => doSearch(params, true)}
            baseSearchName={'requestname'}
            searchType={['base', 'advanced']}
            getFormUrl={'/api/odoc/odocAccountList/getCondition'}
            searchParams={{ isNew: true }}
            searchCustomRender={this.searchCustomRender}
          />

          {/*
						// 这段代码先别删  --kl2018
						<WeaSearchPanel
							searched={accountListStore.searchStore.searched}
							inputValue={accountListStore.getSearchsBaseValue()}
							onSearch={v => accountListStore.doSearch(v)}
							onSearchChange={v => accountListStore.setSearchsBaseValue(v)}
							buttonsAd={this.renderSearchAdButtons()}
							searchsAd={<SearchComponent searchStore={accountListStore.searchStore} />}
							visible={accountListStore.searchStore.showSearchAd}
							onVisibleChange={v => accountListStore.searchStore.changeShowSearchAd(v)}
						/>
					*/}
          {this.getTable()}
        </WeaTop>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@vgpd55`}
          title={getLabel(388097, '收文单位信息')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={() => changeDailogStatus()}
          visible={visiable}
          style={{ width: '50%', height: '600' }}
          buttons={this.getDailogBtn()}
          hasScroll
        >
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ih8zcs`}
            searchType={['base']}
            keyParam="viewcondition" // 主键
            onSearch={value => getDialogTable(value)}
          />
          <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@bypgfv`}
            comsWeaTableStore={tableStore}
            rowSelection={{
              selectedRowKeys,
              onChange: rowSelection,
            }}
            onOperatesClick={onOperatesClick}
          />
        </WeaDialog>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@o375tf`}
          title={getLabel(388128, '撤销公文')}
          onCancel={() => ReasonDialogStatus()}
          visible={reasonDialogShow}
          style={{ width: 750, height: '212px' }}
          // maskClosable={true}
          icon="icon-coms-official"
          buttons={
            [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0j0spm@undo`} type="primary" onClick={() => repeal()}>{getLabel('23757', '撤销')}</Button>]
          }
          className="sendDoc_rejectReason"
        >
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@h568b6`} ref="scroll" className="rejectReason">
            {backoutForm.render({ needTigger: false })}
          </WeaNewScroll>
        </WeaDialog>

      </WeaRightMenu>
    );
  }

  expandedRow = (record) => {
    const { accountListStore } = this.props;
    const { subWFDatas, requestSubWFed } = accountListStore;
    let rows = [];
    if (Object.keys(subWFDatas).length > 0) {
      for (let i in subWFDatas) {
        if (i.includes(`${record.requestid}_`)) {
          rows.push(
            <div className="wea-table-child-acc">
              <div className="left">
                <p title={subWFDatas[i].odoctypename}>{subWFDatas[i].odoctypename}</p>
              </div>
              <div className="right">
                <div className="right-top">
                  <a dangerouslySetInnerHTML={{ __html: subWFDatas[i].showlink }} />
                </div>
                <div className="right-bottom">
                  {subWFDatas[i].creatershowname}： <a dangerouslySetInnerHTML={{ __html: subWFDatas[i].creater }} />
								&nbsp;&nbsp;&nbsp;&nbsp;
										{subWFDatas[i].createdatetimeshowname}：{subWFDatas[i].createdatetime}
								&nbsp;&nbsp;&nbsp;&nbsp;
								当前节点：审批&nbsp;&nbsp;&nbsp;&nbsp;
										{subWFDatas[i].unoperatorsshowname}：<a className="right-bottom-unoperators" dangerouslySetInnerHTML={{ __html: subWFDatas[i].unoperators }} />
                </div >
              </div>
            </div>,
          );
        }
      }
      if (rows.length > 0) {
        return (<div className="wea-table-child-acc-parent">{rows}</div>);
      }
    } else if (record.subrequestInfospan == '1') {
      return (
        <div className="wea-table-child-acc-parent accountList-loading">
          {
            !requestSubWFed && <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@jrbung`} />
          }
        </div>
      );
    }
  }

  getDailogBtn() {
    const { selectedRowKeys, ReasonDialogStatus, postOther } = this.props.accountListStore;
    const disabled = !(selectedRowKeys.length > 0);
    return (
      [
        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@2bqn1x@selectBrowser`}
          title={getLabel('388123', '选择单位')}
          type={142}
          customized
          isSingle={false}
          onChange={postOther}
        >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yw6vk1@sendOther`} type="primary">{getLabel('388098', '发送其他单位')}</Button>
        </WeaBrowser>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@exwa5u@batchUndo`} type="primary" disabled={disabled} style={{ marginLeft: 15 }} onClick={ReasonDialogStatus}>{getLabel('388099', '批量撤销')}</Button>,
      ]
    );
  }

  getTable = (showPagination = true) => {
    const { accountListStore } = this.props;
    const pagination = showPagination ? null : { pagination: false };
    return (
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@u5i38j`}
        columns={accountListStore.columns}
        defaultExpandAllRows={true}
        expandedRowRender={this.expandedRow}
        dataSource={accountListStore.datas}
        pagination={{ // 分页
          current: accountListStore.current,
          total: accountListStore.count, // 数据总数量
          pageSize: accountListStore.pageSize, // 显示几条一页
          defaultPageSize: accountListStore.pageSize, // 默认显示几条一页
          showQuickJumper: true,
          showSizeChanger: true, // 是否显示可以设置几条一页的选项
          onShowSizeChange: accountListStore.changeShowSize, // 当几条一页的值改变后调用函数，current：改变显示条数时当前数据所在页；pageSize:改变后的一页显示条数
          onChange: this.tablePageChange,
          showTotal() { // 设置显示一共几条数据
            return `${getLabel('18609', '共')} ${accountListStore.count} ${getLabel('18256', '条')}`;
          },
        }}
        loading={accountListStore.loading}
        onChange={this.tableChange}
        {...pagination}
      />
    );
  }

  searchCustomRender = (form, condtion,fns) => {
    const { accountListStore } = this.props;
    let group = [];
    form.isFormInit && toJS(condtion).map((c, index) => {
      let items = [];
      c.items.map((field) => {
        let col = 2;
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wb4rhi@${field.domkey[0]}`}
            label={`${field.label}`}
            labelCol={{ span: `${field.labelcol}` }}
            ratio1to2
            error={form.getError(field)}
            tipPosition="bottom"
            wrapperCol={{ span: `${field.fieldcol}` }}
          >
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ejevrj@${field.domkey[0]}`}
              fieldConfig={field}
              form={form}
              onEnterSearch={() => {
                const params = form.getFormParams();
                fns.closeSearch();
                accountListStore.doSearch(params, true);
              }}
              { ...fns }
            />
          </WeaFormItem>),
          col,
          hide: form.isHide(field, (keys, allParams) => {
            if (allParams.officalType == '') {
              if (field.label == getLabel('382363', '签报环节') || field.label == getLabel('382362', '收文环节') || field.label == getLabel('382361', '发文环节')) return true;
            }
            if (allParams.officalType == '1') {
              if (field.label == getLabel('382363', '签报环节') || field.label == getLabel('382362', '收文环节')) return true;
            }
            if (allParams.officalType == '2') {
              if (field.label == getLabel('382363', '签报环节') || field.label == getLabel('382361', '发文环节')) return true;
            }
            if (allParams.officalType == '3') {
              if (field.label == getLabel('382362', '收文环节') || field.label == getLabel('382361', '发文环节')) return true;
            }
            return false;
          }),
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@lqfdeu@${index}`} needTigger={false} title={c.title} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }

  tablePageChange = (current) => {
    // 点击改变页数的选项时调用函数，current:将要跳转的页数
    // 处理分页跳转
    const { accountListStore } = this.props;
    const params = this.tabComp ? this.tabComp.wrappedInstance.getFormParams() : {};
    accountListStore.changeShowSize(current, accountListStore.pageSize, params);
  }

  tableChange = (paginations, filters, sorter) => {
    // 处理排序
    const { accountListStore } = this.props;
    if (sorter.column && sorter.order) {
      accountListStore.setOrderkey(sorter.column.orderkey);
      accountListStore.setSortOrder(sorter.order);
      accountListStore.doSearch(this.tabComp.wrappedInstance.getFormParams());
    }
  }
}


export default AccountListComponent;

